﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace SparklineGenerator.Controllers
{
    public class SparkGen
    {
        private static readonly char[] Ticks = {'▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'};
        public static string GetSparkline(string data)
        {
            var dataStrSeq = Regex.IsMatch(data, @"[0-9 ,.]+") ? (data.Contains(',') ? data.TrimEnd().TrimStart().Split(',').ToList() : data.TrimEnd().TrimStart().Split(' ').ToList()): null;
            if (dataStrSeq == null) return null;
            var dataSeq = data.Contains('.') ? dataStrSeq.ConvertAll(double.Parse).ConvertAll(Convert.ToInt32) : dataStrSeq.ConvertAll(int.Parse);
            var max = dataSeq.Max();
            var min = dataSeq.Min();
            var m = (max - min) + 1;
            var step = m / Ticks.Length;
            if (step == 0) step = 1;
            var brackets = new List<int[]>();
            var firstStep = min;
            for (var i = 0; i <= Ticks.Length - 2; i++)
            {
                brackets.Add(new[] { firstStep, firstStep + step });
                firstStep += step;
            }
            brackets.Add(new[] {max, max+1});
            var sb = new StringBuilder();
            var tickC = 0;
            foreach (var d in dataSeq)
            {
                foreach (var bracket in brackets)
                {
                    if (d >= bracket[0] && d < bracket[1])
                    {
                        sb.Append(Ticks[tickC]);
                        break;
                    }
                    tickC++;
                }
                tickC = 0;
            }
            return sb.ToString();
        }
    }
}
